package com.vincent.template.service.security.impl;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.vincent.template.commons.base.VctTriple;
import com.vincent.template.domain.SysAuthPo;
import com.vincent.template.domain.SysBindAuthUriPo;
import com.vincent.template.domain.SysUriPo;
import com.vincent.template.repository.SysAuthRepository;
import com.vincent.template.repository.SysBindAuthUriRepository;
import com.vincent.template.repository.SysUriRepository;
import com.vincent.template.service.security.AuthUriService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author Vincent Wang
 * @date 2021/1/15 19:55
 */
@Service
public class AuthUriServiceImpl implements AuthUriService {

    @Autowired
    private SysUriRepository uriRepository;
    @Autowired
    private SysBindAuthUriRepository bindAuthUriRepository;
    @Autowired
    private SysAuthRepository authRepository;

    /**
     * 查询所有的uri配置
     * @return
     */
    @Override
    public List<VctTriple<Long, String, String>> findUris() {
        List<SysUriPo> uris = uriRepository.findAll();
        if (CollectionUtils.isEmpty(uris)) {
            return Lists.newArrayList();
        }
        return uris.stream()
                .map(uri -> VctTriple.of(uri.getId(), uri.getPattern(), uri.getMode()))
                .collect(Collectors.toList());
    }

    /**
     * 查询所有的权限和uri资源绑定数据
     * @return
     */
    @Override
    public Map<String, Set<Long>> findAuthUrisMap() {
        List<SysBindAuthUriPo> authUriBindings = bindAuthUriRepository.findAll();
        if (CollectionUtils.isEmpty(authUriBindings)) {
            return Maps.newHashMap();
        }
        Map<Long, Set<Long>> authUrisMap = authUriBindings.stream().collect(Collectors
                .groupingBy(SysBindAuthUriPo::getAuthId, Collectors
                        .mapping(SysBindAuthUriPo::getUriId, Collectors.toSet())));
        List<SysAuthPo> auths = authRepository.findAllById(authUrisMap.keySet());
        Map<Long, String> authMap = auths.stream()
                .collect(Collectors.toMap(SysAuthPo::getId, SysAuthPo::getCode));
        return authUrisMap.entrySet().stream().collect(Collectors
                .toMap(e -> authMap.get(e.getKey()), Map.Entry::getValue));
    }
}
